package com.hxit.huaxiamelongarden.service.impl;

import com.hxit.huaxiamelongarden.domin.po.SearchHistory;
import com.hxit.huaxiamelongarden.mapper.HotSearchHistoryMapper;
import com.hxit.huaxiamelongarden.service.HotSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName HotSearchServiceImpl
 * @description 热搜榜逻辑实现类
 * @Author 12694
 * @Date 2025/1/29 12:04
 * @Version 1.0
 **/
@Service
public class HotSearchServiceImpl implements HotSearchService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private HotSearchHistoryMapper hotSearchHistoryMapper;
    private static final String HOT_SEARCH_KEY = "hot_search";  // Redis key用于保存热搜数据

    @Override
    public void incrementHotSearch(String keyword) {
        // 将关键词存入 Redis 中，值是增量
        redisTemplate.opsForZSet().incrementScore(HOT_SEARCH_KEY, keyword, 1);
        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setKeyword(keyword);
        hotSearchHistoryMapper.insert(searchHistory);
    }

    //获取热搜词汇
    @Override
    public Set<Object> getHotSearch() {
        // 获取排序后的热搜列表，最多返回8个
        return redisTemplate.opsForZSet().reverseRange(HOT_SEARCH_KEY, 0, 7);
    }
    // 更新热搜榜，给 Redis 加时间过期（TTL）
    public void setHotSearchTTL(long time, TimeUnit timeUnit) {
        redisTemplate.expire(HOT_SEARCH_KEY, time, timeUnit);
    }
}
